import { LintGuard } from './precessor'
import { Command } from 'commander'
import { resolve } from 'path'
import { readFileSync } from 'fs-extra'
import { printError, printInfo, printSuccess } from './formatter'
import { fileURLToPath } from 'url'
import { dirname } from 'path'
import { getConfigFile } from './config'
// 获取当前文件的路径
const __filename = fileURLToPath(import.meta.url)
// 获取当前文件所在的目录
const __dirname = dirname(__filename)
const program = new Command()
// 解析 package.json 获取版本信息
const packageJsonPath = resolve(__dirname, '../package.json')
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'))
program
    .name('lint-guard')
    .version(packageJson.version)
    .description('A custom wrapper for lint-staged with extended functionality')
    .option('-c, --config <path>', 'Path to configuration file')
    .option('--no-stash', 'Disable Git stash')
    .option('--quiet', 'Disable lint-staged output')
    .option('--debug', 'Enable debug mode')
    .option('--shell', 'Run commands in shell')
    .action(async (options) => {
        try {
            const configObj = await getConfigFile(options.config || resolve('./.hawk'))
            // 创建自定义 lint-staged 实例
            const lintWrapper = new LintGuard({
                config: configObj,
                stash: options.stash !== undefined ? options.stash : true,
                quiet: options.quiet,
                debug: options.debug,
                shell: options.shell,
                beforeHooks: [
                    async () => {
                        printInfo('🚀 开始执行 lint-staged 检查')
                    }
                ],
                afterHooks: [
                    async (success) => {
                        if (success) {
                            printSuccess('🎉 验证完成，可以提交代码')
                        } else {
                            printError('❌ 验证失败，请修复问题后再提交')
                        }
                    }
                ]
            })
            // 执行 lint-staged
            const success = await lintWrapper.execute()
            process.exit(success ? 0 : 1)
        } catch (error) {
            printError('❌ 执行过程中发生错误:', error)
            process.exit(1)
        }
    })

program.parse(process.argv)
